package com.linkage.jz.bankruptcy.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.StateListDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.DocTmpListActivity;
import com.linkage.jz.bankruptcy.activity.Main.LawListActivity;
import com.linkage.jz.bankruptcy.activity.Main.ToolsActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingReadMeActivity;
import com.linkage.jz.bankruptcy.activity.Project.CreateProjectActivity;
import com.linkage.jz.bankruptcy.activity.Project.ProDetailActivity;
import com.linkage.jz.bankruptcy.bean.ADInfo;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.bean.MyProInfoAuth;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.CycleViewPager;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ViewFactory;
import com.linkage.seapeak.activity.message.GoToPageLoadingActivity;
import com.linkage.seapeak.activity.register.RegisterActivity;
import com.linkage.seapeak.pojo.TempProject;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by caobotao on 16/1/4.
 */
public class MainFragment extends BaseFragment implements View.OnClickListener {

    private ViewGroup mMoreLayout;
    private List<ImageView> views = new ArrayList<ImageView>();
    private List<ADInfo> infos = new ArrayList<ADInfo>();
    private CycleViewPager cycleViewPager;
    private static boolean frist = true;
    private View mView;
    private LinearLayout ll_myweb, ll_intro, ll_main_bt1, ll_main_bt2, ll_main_bt3, ll_main_bt4, ll_main_bt5, ll_main_bt6;

//    private String[] imageUrls = {};

    private ArrayList<String> imageUrls = new ArrayList<String>();
    private ArrayList<String> showUrls = new ArrayList<String>();
    private LinearLayout noticeLayout;
    private TextView noticeContent;
    private ImageView closeNotice;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.fragment_tab_main, container, false);
            configImageLoader();
            initialize();
            setupViews();
            ll_myweb = mView.findViewById(R.id.ll_myweb);
            ll_intro = mView.findViewById(R.id.ll_intro);
            ll_main_bt1 = mView.findViewById(R.id.ll_main_bt1);
            ll_main_bt2 = mView.findViewById(R.id.ll_main_bt2);
            ll_main_bt3 = mView.findViewById(R.id.ll_main_bt3);
            ll_main_bt4 = mView.findViewById(R.id.ll_main_bt4);
            ll_main_bt5 = mView.findViewById(R.id.ll_main_bt5);
            ll_main_bt6 = mView.findViewById(R.id.ll_main_bt6);
            noticeLayout = (LinearLayout) mView.findViewById(R.id.notice_layout);
            noticeContent = (TextView) mView.findViewById(R.id.notice_content);
            noticeContent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    RefreshEvent event = new RefreshEvent();
                    event.setType(RefreshEvent.TYPE_TASK);
                    EventBus.getDefault().post(event);
                }
            });
            closeNotice = (ImageView) mView.findViewById(R.id.close_notice);
            closeNotice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    noticeLayout.setVisibility(View.GONE);
                }
            });

            ll_myweb.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    showWeb("http://www.poxiao.com");
                }
            });

            ll_intro.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    PersonSettingReadMeActivity.start(getActivity());
                }
            });
            EventBus.getDefault().register(this);


//                    getProjectDetail("a5f23c7746e949988d9893904524545e",1);
        }
        return mView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //在界面销毁的地方要解绑
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onResume() {
        super.onResume();
        //在界面销毁的地方要解绑
        getProjectNotice();


    }

    @Subscribe
    public void getEventBus(Integer num) {
        if (num != null) {
            if (num == Consts.EVENTSHOWTOPIMG) {
                if (imageUrls.size() < 1) {
                    initialize();
                }

            }
            //这里拿到事件之后吐司一下
            //            Toast.makeText(getActivity(), "num" + num, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取项目通知
     * {
     * "projecrName":"项目A",
     * "projecrId":"0001"
     * }
     */
    PublicNoticeDialog noticeDialog;
    private void getProjectNotice() {
        Network.getAPIService()
                .getProjectNotice(getUserToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
//                        json = new Gson().fromJson("{\"code\":0,\"msg\":\"system.success\",\"data\":[{\"projectName\":\"测试2破产清算案\",\"projectId\":\"fec77285876a4b2cbcb98879b92da0a7\"}]}", JsonObject.class);
                        Log.i("zhong", "getProjectNotice onNext: " + json.toString());
                        if (json.get("code").getAsInt() == 0) {
                            JsonArray array = json.getAsJsonArray("data");
                            if (array != null && array.size() == 1) {
                                JsonObject object = array.get(0).getAsJsonObject();
                                final String projecrName = object.get("projectName").getAsString();
                                final String projecrId = object.get("projectId").getAsString();
                                noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        switch (v.getId()) {
                                            case R.id.ll_close:
                                                noticeDialog.dismiss();
                                                break;

                                            case R.id.btn_chancel_notice:
                                                getProjectDetail(projecrId, 1);
                                                noticeDialog.dismiss();
                                                break;

                                            case R.id.btn_save_notice:
//                                                getProjectDetail(projecrId, 0);
                                                noticeDialog.dismiss();
                                                break;

                                        }
                                    }
                                }, 1, "提示", "您已加入" + projecrName + "，现在可以线上操作啦~",
                                        "现在申报", "我先看看");
                                noticeDialog.show();
                                noticeLayout.setVisibility(View.GONE);
                            } else if (array != null && array.size() != 0) {
                                noticeContent.setText("您已加入" + array.size() + "个新项目，可以线上操作啦~");
                                noticeLayout.setVisibility(View.VISIBLE);
                            } else
                                noticeLayout.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    /**
     * 通过iD获取项目 3007
     * @param projectId
     */
    private void getProjectDetail(String projectId, int toPage) {
        Network.getAPIService()
                .getDetailInfo(getUserToken(), projectId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            return;
                        } else {
                            try {
                                TempProject tempProject = new Gson().fromJson(json.getAsJsonObject("data")
                                        .toString(), TempProject.class);
                                //少了用户身份
                                MyProInfoAuth auth =  new Gson().fromJson(json.getAsJsonObject("data")
                                        .getAsJsonObject("auth").toString(), MyProInfoAuth.class);
                                MyProInfo mInfo = new MyProInfo();
                                mInfo = tempProject.turnData(mInfo);
                                mInfo.setAuth(auth);
                                if (toPage == 1) {
                                    Intent intent = new Intent(getActivity(), ProDetailActivity.class);
                                    intent.putExtra("info", new Gson().toJson(mInfo));
//                                    intent.putExtra("info", new Gson().toJson(mInfo));
                                    startActivity(intent);
                                } else {
                                    Intent intent = new Intent(getActivity(), ProDetailActivity.class);
                                    intent.putExtra("info", new Gson().toJson(mInfo));
                                    startActivity(intent);
                                }
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });

    }

    @SuppressLint("NewApi")
    private void initialize() {

        try {
            String baseUrl = SPUtils.getInstance(Consts.SPNAME).getString("bannerbaseUrl");
            String links = SPUtils.getInstance(Consts.SPNAME).getString("bannerlinks");
            JSONArray ary = new JSONArray(links);
//            JSONArray ary = obj.getJSONArray("links");
            imageUrls = new ArrayList<String>();
            for (int i = 0; i < ary.length(); i++) {
                JSONObject obj_str = (JSONObject) ary.get(i);

                String url = obj_str.getString("picurl");
                url = baseUrl + "" + url;
                imageUrls.add(url);

                String showurl = obj_str.getString("url");
                url = baseUrl + "" + url;
                showUrls.add(url);


            }


        } catch (Exception ex) {
            ex.printStackTrace();
        }


        cycleViewPager = (CycleViewPager) getActivity().getFragmentManager()
                .findFragmentById(R.id.fragment_cycle_viewpager_content);

        if (imageUrls.size() < 1) {
            return;
        }
        for (int i = 0; i < imageUrls.size(); i++) {
            ADInfo info = new ADInfo();
            info.setUrl(imageUrls.get(i));
            info.setContent("图片-->" + i);
            infos.add(info);
        }

        // 将最后一个ImageView添加进来
        views.add(ViewFactory.getImageView(getActivity(), infos.get(infos.size() - 1).getUrl()));
        for (int i = 0; i < infos.size(); i++) {
            views.add(ViewFactory.getImageView(getActivity(), infos.get(i).getUrl()));
        }
        // 将第一个ImageView添加进来
        views.add(ViewFactory.getImageView(getActivity(), infos.get(0).getUrl()));

        // 设置循环，在调用setData方法前调用
        cycleViewPager.setCycle(true);

        // 在加载数据前设置是否循环
        cycleViewPager.setData(views, infos, mAdCycleViewListener);
        //设置轮播
        cycleViewPager.setWheel(true);

        // 设置轮播时间，默认5000ms
        cycleViewPager.setTime(2000);
        //设置圆点指示图标组居中显示，默认靠右
        cycleViewPager.setIndicatorCenter();
    }

    private CycleViewPager.ImageCycleViewListener mAdCycleViewListener = new CycleViewPager.ImageCycleViewListener() {

        @Override
        public void onImageClick(ADInfo info, int position, View imageView) {
            if (cycleViewPager.isCycle()) {
                position = position - 1;
//                showWeb(info.getUrl());
//                Toast.makeText(getActivity(),
//                        "position-->" + info.getContent(), Toast.LENGTH_SHORT)
//                        .show();
            }

        }

    };

    /**
     * 配置ImageLoder
     */
    private void configImageLoader() {
        // 初始化ImageLoader
        @SuppressWarnings("deprecation")
        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.icon_stub) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.icon_empty) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.icon_error) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
                // .displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
                .build(); // 创建配置过得DisplayImageOption对象

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity().getApplicationContext()).defaultDisplayImageOptions(options)
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
    }

    private void setupViews() {
//        setContentView(R.layout.activity_main);
        mMoreLayout = (ViewGroup) mView.findViewById(R.id.layout_more);   //找到该容器（这里的控件为LinearLayout，转换为ViewGroup是因为ViewGroup是容器的基类）

        /**
         * 由于文字也是动态生成，这里用数组比较多余，使用android中array文件定义资源文件，并取出(便于管理，文字和代码分开，日后要修改直接找资源数组文件便可，不用找代码)
         */
        final String[] categories = getResources().getStringArray(R.array.categories);


        final int size = categories.length;     //数组的个数
        final int rowCount = size / 2;          // 需要布局的行数(每行三个)

        /**
         * 动态添加布局方法封装
         * 参数 1.父容器    2.资源文字数组  3.从第几个开始   4.行数
         */
        fillViews(mMoreLayout, categories, 0, 3);
    }

    private void fillViews(ViewGroup layout, String[] categories, int start, int end) {
        // 表格第一条线
        View.inflate(getActivity(), R.layout.layout_line_horizonal, layout);

        for (int i = start; i < end; i++) {

            //找到索引，便于根据索引添加图片文件和文字
            final int firstIndex = i * 2;
            final int secondIndex = i * 2 + 1;

            final String firstCategory = categories[firstIndex];
            final String secondCategory = categories[secondIndex];

            //这里控制的是加载本地图片，通过应用包命找到 有规则命名的图片资源文件（注意：有规则命名的图片文件）
            //--->因为这里有两种效果，一是默认的图片，二是按下触发后的图片和文字，所以这里一个条目要 getResources()两次
            final int firstDrawableNormal = getResources().getIdentifier(String.format("home_icon%01d",
                    firstIndex + 1), "drawable", getActivity().getApplicationContext().getPackageName());
            final int secondDrawableNormal = getResources().getIdentifier(String.format("home_icon%01d",
                    secondIndex + 1), "drawable", getActivity().getApplicationContext().getPackageName());
            final int firstDrawablePressed = getResources().getIdentifier(String.format("home_icon%01d",
                    firstIndex + 1), "drawable", getActivity().getApplicationContext().getPackageName());
            final int secondDrawablePressed = getResources().getIdentifier(String.format("home_icon%01d",
                    secondIndex + 1), "drawable", getActivity().getApplicationContext().getPackageName());

            //这里是将上面找到的   默认图片  和  按下时的图片 放入到  StateListDrawable缓存中
            final StateListDrawable firstDrawable = new StateListDrawable();
            firstDrawable.addState(new int[]{android.R.attr.state_pressed}, getResources().getDrawable(firstDrawablePressed));
            firstDrawable.addState(new int[]{}, getResources().getDrawable(firstDrawableNormal));

            final StateListDrawable secondDrawable = new StateListDrawable();
            secondDrawable.addState(new int[]{android.R.attr.state_pressed}, getResources().getDrawable(secondDrawablePressed));
            secondDrawable.addState(new int[]{}, getResources().getDrawable(secondDrawableNormal));


            // 父布局
            final LinearLayout linearLayout = new LinearLayout(getActivity());

            // 第一个子布局
            View.inflate(getActivity(), R.layout.layout_line_vertical, linearLayout);
            View.inflate(getActivity(), R.layout.layout_department, linearLayout);
            View.inflate(getActivity(), R.layout.layout_line_vertical, linearLayout);

            // 第二个子布局
            View.inflate(getActivity(), R.layout.layout_department, linearLayout);
            View.inflate(getActivity(), R.layout.layout_line_vertical, linearLayout);


            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layout.addView(linearLayout, layoutParams);

            // 表格最后一条线
            View.inflate(getActivity(), R.layout.layout_line_horizonal, layout);

            //根据索引getChildAt到指定的位置
            final View firstView = linearLayout.getChildAt(1);
            firstView.setTag(firstIndex + 1 + "");        //设置tag，便于在后面判断点击的哪一个
            firstView.setOnClickListener(this);     //设置点击
            final TextView firstTextView = (TextView) firstView.findViewById(R.id.text_title);
            firstTextView.setText(firstCategory);   //设置文字
            final ImageView firstImageView = (ImageView) firstView.findViewById(R.id.image_icon);
            firstImageView.setImageDrawable(firstDrawable); //将之前缓存的图片设置出来

            final View secondView = linearLayout.getChildAt(3);
            secondView.setTag(secondIndex + 1 + "");
            secondView.setOnClickListener(this);
            final TextView secondTextView = (TextView) secondView.findViewById(R.id.text_title);
            secondTextView.setText(secondCategory);
            final ImageView secondImageView = (ImageView) secondView.findViewById(R.id.image_icon);
            secondImageView.setImageDrawable(secondDrawable);


        }
    }

    private int showWeb(String url) {
        int ret = -1;
        try {
            Uri uri = Uri.parse(url);
            startActivity(new Intent(Intent.ACTION_VIEW, uri));
            ret = 0;
        } catch (Exception e) {

        }
        return ret;
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.ll_close:
                    noticeDialog.dismiss();
                    break;

                case R.id.btn_chancel_notice:
//                   Boolean flag =  noticelxDialog.cb_agree.isChecked();
                    noticeDialog.dismiss();

                    break;

                case R.id.btn_save_notice:
                    RegisterActivity.start(getActivity());
                    noticeDialog.dismiss();
                    break;

            }
        }
    };

    /* (non-Javadoc)
     * @see app.ui.TitleActivity#onClick(android.view.View)
     */
//    @Override
    public void onClick(View v) {
        final Object tag = v.getTag();      //通过之前setTag找到点击位置
        if (tag != null) {
            String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
            String department = (String) tag;
            if ("1".equalsIgnoreCase(department)) {
//                Intent intent = new Intent(getActivity(), PDFViewActivity.class);
//                getActivity().startActivity(intent);

                if ("".equalsIgnoreCase(userToken)) {
                    noticeDialog = new PublicNoticeDialog(getActivity(), onClickListener,
                            1, "提示", "操作此功能，需要请您先注册/登录",
                            "取消", "确认");
                    noticeDialog.show();
                    return;
                }

                CreateProjectActivity.start(getActivity());

            } else if ("2".equalsIgnoreCase(department)) {
                LawListActivity.start(getActivity());
//                Intent intent = new Intent(getActivity(), ProVoteMainActivity.class);
//                startActivity(intent);
            } else if ("3".equalsIgnoreCase(department)) {
                if ("".equalsIgnoreCase(userToken)) {
                    noticeDialog = new PublicNoticeDialog(getActivity(), onClickListener,
                            1, "提示", "操作此功能，需要请您先注册/登录",
                            "取消", "确认");
                    noticeDialog.show();
                    return;
                }
//                MyProListActivity.start(getActivity());
                RefreshEvent event = new RefreshEvent();
                event.setType(RefreshEvent.TYPE_MY_PRO);
                EventBus.getDefault().post(event);
            } else if ("4".equalsIgnoreCase(department)) {
                ToolsActivity.start(getActivity());

            } else if ("5".equalsIgnoreCase(department)) {
//                PublicProListActivity.start(getActivity());
                RefreshEvent event = new RefreshEvent();
                event.setType(RefreshEvent.TYPE_PU_PRO);
                EventBus.getDefault().post(event);
            } else if ("6".equalsIgnoreCase(department)) {
                DocTmpListActivity.start(getActivity());
            }
        } // else ignored
    }

}
